<?php

class Upgrade_DatabaseController extends Zend_Controller_Action
{
    protected $table_name_arr = array();

    function init()
    {
        ini_set('max_execution_time',0);
        ini_set('memory_limit','200M');
        error_reporting(E_ALL & ~E_NOTICE);

        $this->table_name_arr = array(
        'SchoolRoom' => '學校處室',
        'TeacherTitle' => '教師職稱',
        'TeacherBase' => '教師資料',
        'Schoolday' => '學期日期設定' ,
        'SchoolClass' => '班級設定',
        'SemeCourseDate'=> '上課日數',
        'ScoreSetup' => '成績設定',
        'ScoreSs' => '課程設定',
        'StudBase'=> '學生基本資料',
		'StudDomicile'=>'戶口資料',
		'StudSeme' => '學生學期資料',
		'StudAbsent' => '學生出缺席資料',
		'SectionTime' => '課表時間',
		'StudBrotherSister'=>'兄弟姐妹資料',
		'StudKinfolk' => '學生其他親屬資料',
		'StudSemeEduh'=>'學期輔導記錄',
		'StudSemeTalk' => '輔導訪談記錄',
		'StudSemeSpe' => '特殊表現記錄',
        'StudMove' => '學生異動資料',
        'SemeScore'=>'學期成績',
		'ScoreMaster' => '階段成績',
		'ScoreNor' => '平時成績',
        'Elective'    => '分組班課程',
		'SfsText' => '系統選項清單',
        'Comment' => '評語檔案',
        'StudSemeScoreNor' => '日常生活成績及評語'
        );
    }


    function testAction()
    {

        // 升級學校處室
        $tt = new upgrade_SchoolRoom();
        $tt->upgrade();
        // 升級教師職稱
        $tt = new upgrade_TeacherTitle();
        $tt->upgrade();
        exit;
    }

    function indexAction()
    {
        $this->_redirect('upgrade/database/testdb');
    }

    /**
     * 取得升級的資料表
     *
     */
    function tablesAction() {

        $this->_helper->json($this->table_name_arr);
    }


    /**
     * 執行升級
     *
     */
    function upAction()
    {
        $table = $this->_request->getParam('table');
        $class = "Default_Model_Upgrade_$table";
        $tb = new $class();
        $res = $tb->upgrade();

        $arr['id']= $table;
        $arr['item']  = $this->table_name_arr[$table];
        $arr['result'] = $res;
        $this->_helper->json($arr);
    }

    /**
     * 查詢資料筆數
     * @return unknown_type
     */
    function statusAction()
    {
        $table = $this->_request->getParam('table');
        $arr = array();
        if ($table) {
            $table= trim(strip_tags($table));
            $class = "Default_Model_Upgrade_$table";
            $tableUpClass = new $class;
            $arr = $tableUpClass->getTargetTableRows();

        }
        $this->_helper->json($arr);
    }

    function updbAction()
    {
        //TODO 檢查資料庫帳密是否正確 , 掃描已升級的資料表
        $this->view->tableArr = Zend_Json::encode(array_keys($this->table_name_arr));

    }

    function testdbAction()
    {

        $resetdb = $this->_request->getParam('resetdb');
        // 判斷資料庫設定檔 sfs3dbset 是否存在? 或可連接?
        if (is_file(Bootstrap::getPath('data').'/sfs3dbset') and $resetdb==''){
            $str = file_get_contents(Bootstrap::getPath('data').'/sfs3dbset');
            $arr = unserialize($str);
            if ($link=@mysql_connect($arr['host'],$arr['username'],$arr['password'])){
                if (@mysql_select_db($arr['dbname']))
                $this->_redirect('upgrade/database/updb');
            }

        }
    }

    function setdbAction()
    {
        $res=$this->setdb();
        $this->_helper->json($res);

    }

    /**
     * 設定資料庫
     *
     * @return unknown
     */
    private function setdb()
    {
        $host = $this->_request->getParam('host');
        $dbname = $this->_request->getParam('dbname');
        $user = $this->_request->getParam('user');
        $password = $this->_request->getParam('password');
        $link = @mysql_connect($host,$user,$password);
        if (!$link) {
            $msg =  '資料庫帳號密碼有誤!';

        }
        else if (@mysql_select_db($dbname,$link)){
            $arr2['host'] = $host;
            $arr2['dbname'] = $dbname;
            $arr2['username'] = $user;
            $arr2['password'] = $password;
            file_put_contents(Bootstrap::getPath('data').'/sfs3dbset',serialize($arr2));
            chmod(Bootstrap::getPath('data').'/sfs3dbset',0600);
            $msg = "設定正確";
        }
        else {
            $msg =  '找不到資料庫!';

        }

        $arr['msg'] = $msg;

        return $arr;
    }


    function subjectAction()
    {
        $str = file_get_contents(Bootstrap::getPath('data').'/sfs3dbset');
        $arr = unserialize($str);
        $sfs3db = new Zend_Db_Adapter_Pdo_Mysql($arr); // sfs3 資料庫
        echo "<pre>";
        //$db = Zend_Db_Table::getDefaultAdapter();
        $res = $sfs3db->query("select b.subject_name,a.* from score_ss a ,score_subject b where a.scope_id=b.subject_id and a.subject_id >0")->fetchAll();
        //$subject = new Semester_Model_SemesterCourse();
        foreach($res as $row) {
            $year= $row['year'];
            $semester = $row['semester'];
            $grade = $row['class_year'];
            echo $row['subject_name'].'-';
            //  $arr = $subject->getSemesterSubject($year,$semester,$grade);
            //  print_r($arr);
        }
        exit;
    }


}